package HuffmanTree;

/**
 * Arbol para codificacion Huffman. 
 * @author duane a. bailey
 * Modificado por Vinicio Gomez
 * @since 13/09/2012
 * @version 1.0
 * 
 */
class huffmanTree implements Comparable<huffmanTree>
{
    BinaryTree<Node> empty;
    BinaryTree<Node> root; // root of tree
    int totalWeight;     // weight of tree

    public huffmanTree(Node e)
    // post: construct a node with associated character
    {
        empty = new BinaryTree<Node>();
        root = new BinaryTree<Node>(e,empty,empty);
        totalWeight = e.getFreq();
    }

    public huffmanTree(huffmanTree left, huffmanTree right)
    // pre: left and right non-null
    // post: merge two trees together and merge their weights
    {
        this.totalWeight = left.totalWeight + right.totalWeight;
        root = new BinaryTree<Node>(new Node(totalWeight),left.root,right.root);
    }

    @Override
    public int compareTo(huffmanTree other)
    // pre: other is non-null
    // post: return integer reflecting relation between values
    {
        huffmanTree that = (huffmanTree)other;
        return this.totalWeight - that.totalWeight;
    }

    @Override
    public boolean equals(Object that)
    // post: return true if this and that are same tree instance
    {
        return this == that;
    }
    
    public void print()
    // post: print out strings associated with characters in tree
    {
        print(this.root,"");
    }

    protected void print(BinaryTree r, String representation)
    // post: print out strings associated with chars in tree r,
    //       prefixed by representation
    {
        if (!r.left().isEmpty())
        {   // interior node
            print(r.left(),representation+"0"); // append a 0
            print(r.right(),representation+"1"); // append a 1
        } else { // node; print encoding
            Node e = (Node)r.value();
            System.out.println("Encoding of "+e.getCh()+" is "+
               representation+" (frequency was "+e.getFreq()+")");
        }
    }
}